#include "adc.h"
void ADCInit(unsigned int ADC_Clk)
{
	SYSMEMREMAP = 0x2;/* remap to internal flash */
	PDRUNCFG &= ~(0x1<<4);//Disable Power down bit to the ADC block. 
	PDRUNCFG &= ~(0x1<<5);/* main system OSC run is cleared, bit 5 in PDRUNCFG register */
	SYSAHBCLKCTRL |= (1<<13);// Enable AHB clock to the ADC.
	SYSAHBCLKCTRL |= (1<<16);/* System clock to the IOCON needs to be enabled or
															most of the I/O related peripherals won't work. */
	IOCON_R_PIO1_2 &= ~0x8F;	
	IOCON_R_PIO1_2 |= 0x02; /* ADC IN3 */
	AD0CR = ( 0x01 << 3 ) |  /* SEL=1,select channel 3 on ADC0 */
	( ( 12000000 / ADC_Clk - 1 ) << 8 ) |  /* CLKDIV = Fpclk / 2400000 - 1 */ 
	( 0 << 16 ) | 		/* BURST = 0, no BURST, software controlled */
	( 0 << 17 ) |  		/* CLKS = 0, 11 clocks/10 bits */
	( 1 << 21 ) |  		/* PDN = 1, normal operation */
	( 0 << 22 ) |  		/* TEST1:0 = 00 */
	( 0 << 24 ) |  		/* START = 0 A/D conversion stops */
	( 0 << 27 );		/* EDGE = 0 (CAP/MAT singal falling,trigger A/D conversion) */ 
}


unsigned int ADCRead( unsigned char channelNum )
{
  unsigned int regVal = 0, ADC_Data = 0;


  /* channel number is 0 through 7 */
  if ( channelNum >= 8 )
  {
	channelNum = 0;		/* reset channel number to 0 */
  }
  AD0CR &= 0xFFFFFF00;
  AD0CR |= (1 << 24) | (1 << channelNum);	
				/* switch channel,start A/D convert */

  while ( 1 )			/* wait until end of A/D convert */
  {
		regVal = *(volatile unsigned long *) (0x4001C010 + 4 * channelNum);
	/* read result of A/D conversion */
		if ( regVal  & ADC_DONE )
		{
			break;
		}
  }	
        
  AD0CR &= 0xF8FFFFFF;	/* stop ADC now */    
  //if ( regVal & ADC_OVERRUN )	/* save data when it's not overrun, otherwise, return zero */
  //{
		//return ( 0 );
  //}
  ADC_Data = ( regVal >> 6 ) & 0x3FF;
  return ADC_Data;	/* return A/D conversion value */

 
}
